/* pipwrite.c - pipwrite */

#include <xinu.h>
#include <mips.h>
#include <stdio.h>

uint32	pipwrite(
		pipid32         pipid,		/* ID of pipe to connect	*/
		char		buf[],		/* a pointer to the source buf	*/
		uint32		len,		/* length of data to be written	*/
		uint32		begin		/* where to begin store data	*/
	)
{
	intmask mask;                   /* saved interrupt mask			*/
	uint32 lenwri;			/* length of written data to return	*/
	struct pipent *piptr;		/* ptr to pipe's table entry		*/
	int32 i;			/* used for iteration			*/
	int32 temp;
	int32 k;

	mask = disable();		/* saved interrupt mask         */
	lenwri = 0;
	piptr = &piptab[pipid];

	k = begin + len;
	for (i = begin; i < k; i++) {
		temp = i % PIPE_SIZ;
		wait(piptr->psem);
		piptr->pipebuffer[i] = buf[i-begin];
		signal(piptr->csem);
		lenwri++;
	}

	restore(mask);
	return lenwri;
}
